/* 256 个 脉冲一圈*/
#define A1 1      //引脚命名

#define B1 2
#define C1 3
#define D1 4
void(* resetFunc) (void) = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(A1, OUTPUT);  //设置引脚为输出引脚
  pinMode(B1, OUTPUT);
  pinMode(C1, OUTPUT);
  pinMode(D1, OUTPUT);
}

/////////////////////
char buffer [4];
int brightness = 0;
char Temp [4];
void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available()>0 && (Serial.available()<=4)) {

    int responsedatalength = Serial.readBytes(buffer, 4);
    //    要 过滤掉 AT指令
    if (responsedatalength == 4) {
      if (buffer[0] == 43) {
        while (Serial.read() > 0);
      } else {
        brightness = buffer[0] + (buffer[1] << 8) + (buffer[2] << 16) + (buffer[3] << 24);
        //brightness=buffer[3]+(buffer[2]<<8)+(buffer[1]<<16)+(buffer[0]<<24);

        if (brightness >= 0) {
          for (int i = 1; i <= brightness; i++) {
            OneTime(20);

          }
        }
        if (brightness < 0) {
          for (int i = 1; i <= (-brightness); i++) {
            OneTimeRevese(20);
          }
          Serial.print("Nice");
        }

      }
    }
    delay(100);
  }
}






void Phase_A()
{
  digitalWrite(A1, HIGH);   //A1引脚高电平
  digitalWrite(B1, LOW);
  digitalWrite(C1, LOW);
  digitalWrite(D1, LOW);
}

void Phase_B()
{
  digitalWrite(A1, LOW);
  digitalWrite(B1, HIGH);   //B1引脚高电平
  digitalWrite(C1, LOW);
  digitalWrite(D1, LOW);
}

void Phase_C()
{
  digitalWrite(A1, LOW);
  digitalWrite(B1, LOW);
  digitalWrite(C1, HIGH);   //C1引脚高电平
  digitalWrite(D1, LOW);
}

void Phase_D()
{
  digitalWrite(A1, LOW);
  digitalWrite(B1, LOW);
  digitalWrite(C1, LOW);
  digitalWrite(D1, HIGH);   //D1引脚高电平
}

void OneTime(int delayTime) {
  Phase_A();      //设置A相位
  delay(delayTime);
  Phase_B();      //设置B相位
  delay(delayTime);
  Phase_C();      //设置C相位
  delay(delayTime);
  Phase_D();      //设置D相位
  delay(delayTime);
}

void OneTimeRevese(int delayTime) {
  Phase_D();      //设置D相位
  delay(delayTime);
  Phase_C();      //设置C相位
  delay(delayTime);
  Phase_B();      //设置B相位
  delay(delayTime);
  Phase_A();      //设置A相位
  delay(delayTime);
}
